import { PathDTO, SiteDTO, DispatchDTO } from './../../../shared/service-proxy/service-proxies';
import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { ServiceProxy } from '@shared/service-proxy/service-proxies';
import { finalize } from 'rxjs/operators';
import { PathDetailModalComponent } from './path-detail-modal/path-detail-modal.component';
import { SetPathReasonModalComponent } from './set-path-reason-modal/set-path-reason-modal.component';
import * as moment from 'moment';
import { Router } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd';

@Component({
  selector: 'app-path-management',
  templateUrl: './path-management.component.html',
  styleUrls: ['./path-management.component.less']
})


export class PathManagementComponent extends AppComponentBase implements OnInit {
  @ViewChild('pathDetailModal') pathDetailModal: PathDetailModalComponent;
  @ViewChild('setPathReasonModal') setPathReasonModal: SetPathReasonModalComponent
  tableHelper: NzTableHelper;
  sites: SiteDTO[] = [];
  keyword: string;
  startSite: string;
  endSite: string;
  params: string;
  routeParams: any;
  disList: DispatchDTO[];
  constructor(injector: Injector,private modalService: NzModalService, private router: Router, private _service: ServiceProxy) {
    super(injector);
    this.tableHelper = new NzTableHelper();
  }

  ngOnInit() {
    if (!this.isGranted('A8_B23_C30_')) {
      if (this.isGranted('A8_B23_C31_')) {
        this.router.navigate(['/center/path/pathCreate']);
      }
    }

    this.load();
    this.getSites();
  }
  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    this._service.getPagePathsUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, this.keyword, undefined, this.startSite, this.endSite
    ).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result.fieldList;
      this.tableHelper.totalCount = result.result.totalRow;
    });
  }

  reset() {
    this.keyword = undefined;
    this.startSite = undefined;
    this.endSite = undefined;
    this.load();
  }

  showPath(path: PathDTO) {
    this.getCompany(path);
  }

  editStatus(data: PathDTO) {
    this.setPathReasonModal.show(data.id, data.enableFlag);
  }

  getCompany(path: PathDTO) {
    this._service.getSiteUsingGET(path.startSiteId).subscribe(result => {
      const site = result.result;
      this.pathDetailModal.show(path, site.lat, site.lng);
    })
  }

  getSites() {
    this._service.getAllSitesUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    })
  }


  cancel(): void {
    // this.message.info('click cancel');
  }

  confirm(id: string): void {

     this.modalService.confirm({
      nzTitle: this.l('confirm'),
      nzContent: this.l('are_you_sure'),
      nzOkText: 'OK',
      nzOnOk: () => {
        this.delete(id);
      },
      nzOnCancel: () => {

      },
      nzCancelText: this.l('cancel')

    });
    
  }
  delete(id: string) {

    this._service.deletePathUsingDELETE(id).subscribe(result => {
      this.message.success(this.l('delete_success'))
      this.load();
    })
  }
  averageTimeNum: number;
  averageTime(data: PathDTO) {
    this.routeParams = {
      launchsiteId: data.startSiteId, destinationsiteId: data.endSiteId, containerCode: '', containerStatus: [5]
    };

    this.params = JSON.stringify(this.routeParams);

    this._service.searchAllDispatchPageUsingGET(1, 10, this.params
    ).pipe(finalize(() => {
      // this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.disList = result.result.fieldList;
      if (this.disList.length) {
        var totalMin = 0;
        this.disList.forEach(element => {
          const timespan = moment(element.arriveTime).diff(moment(element.launchTime), 'seconds');
          totalMin += timespan / 60;
        });
        data.averageTime = (totalMin / this.disList.length).toString();

        if (data.averageTime.indexOf('.') < 0) {
          data.averageTime += ".0"
        }
      }
    });
  }


}
